package cn.iocoder.yudao.module.lowcode.service.generic;

import cn.iocoder.yudao.module.lowcode.core.event.TableConfigChangeEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 通用表格服务增强器
 * 负责在表配置变更时发布事件，触发 Magic API 接口自动生成
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class GenericTableServiceEnhancer {

    @Resource
    private ApplicationEventPublisher eventPublisher;

    /**
     * 发布表配置变更事件
     *
     * @param tableName 表名
     * @param dataSourceId 数据源ID
     * @param tableComment 表注释
     * @param changeType 变更类型
     * @param autoGenerateApi 是否自动生成API
     */
    public void publishTableConfigChangeEvent(String tableName, Long dataSourceId, String tableComment,
                                            TableConfigChangeEvent.ChangeType changeType, Boolean autoGenerateApi) {
        try {
            TableConfigChangeEvent event = new TableConfigChangeEvent(
                this, tableName, dataSourceId, tableComment, changeType, autoGenerateApi
            );
            
            log.info("[publishTableConfigChangeEvent] 发布表配置变更事件: table={}, dataSourceId={}, changeType={}", 
                    tableName, dataSourceId, changeType);
            
            eventPublisher.publishEvent(event);
            
        } catch (Exception e) {
            log.error("[publishTableConfigChangeEvent] 发布表配置变更事件失败: table={}, dataSourceId={}", 
                    tableName, dataSourceId, e);
        }
    }

    /**
     * 通知表结构创建
     */
    public void notifyTableCreated(String tableName, Long dataSourceId, String tableComment) {
        publishTableConfigChangeEvent(tableName, dataSourceId, tableComment, 
                TableConfigChangeEvent.ChangeType.CREATE, true);
    }

    /**
     * 通知表结构更新
     */
    public void notifyTableUpdated(String tableName, Long dataSourceId, String tableComment) {
        publishTableConfigChangeEvent(tableName, dataSourceId, tableComment, 
                TableConfigChangeEvent.ChangeType.UPDATE, true);
    }

    /**
     * 通知表结构删除
     */
    public void notifyTableDeleted(String tableName, Long dataSourceId, String tableComment) {
        publishTableConfigChangeEvent(tableName, dataSourceId, tableComment, 
                TableConfigChangeEvent.ChangeType.DELETE, true);
    }

    /**
     * 通知字段变更
     */
    public void notifyFieldChanged(String tableName, Long dataSourceId, String tableComment) {
        publishTableConfigChangeEvent(tableName, dataSourceId, tableComment, 
                TableConfigChangeEvent.ChangeType.FIELD_CHANGE, true);
    }
}